package com.drow.aips;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.drow.aips.util.DialogUtil;
import com.drow.aips.util.HttpUtil;

/**
 * 
 * 类名称：Contacts.java
 * <P/>
 * 类描述： 获取通讯录
 * <P/>
 * 创建时间：2012-12-24
 * <P/>
 * 创建人： 史守阳
 * <P/>
 * 联系方式： ssy.vip^qq.com
 * <P/>
 * 修改人：无
 * <P/>
 * 修改时间：无
 * <P/>
 * 修改备注：无
 * <P/>
 * 版本：v1.0
 *
 */
@SuppressLint("WorldReadableFiles")
public class Contacts extends Activity {
	private LinearLayout btn_layout;
	private ExpandableListView expandableListView;
	private List<Map<String, String>> groupArray;
	private List<List<Map<String, String>>> childArray;
	private List<Map<String, Boolean>> groupCheckBox;
	private List<List<Map<String, Boolean>>> childCheckBox;
	private List<Map<String, Object>> btnArray;
	private static final String G_CB = "G_CB";
	private static final String C_CB = "C_CB";
	private static final int TEXTSIZE = 8; //button上字体大小
	private static final int TOUMD = 100; // 0~255透明度值
	private LinearLayout.LayoutParams atEditBtn;

	
	SharedPreferences preferences;
	SharedPreferences.Editor editor;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);
        
     // 获取只能被本应用程序读、写的SharedPreferences对象
     preferences = getSharedPreferences("com.drow.aips", MODE_WORLD_READABLE);
     editor = preferences.edit();
        
        groupArray = new ArrayList<Map<String, String>>();
    	childArray = new ArrayList<List<Map<String, String>>>();
    	groupCheckBox = new ArrayList<Map<String,Boolean>>();
    	childCheckBox = new ArrayList<List<Map<String,Boolean>>>();
    	btnArray = new ArrayList<Map<String,Object>>();
    	btn_layout = (LinearLayout) findViewById(R.id.btn__layout);
    	expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
        
        //初始化groupArray, childArray, groupCheckBox, childCheckBox数据
    	initContacts();

    	final MyExpListAdapter adapter = new MyExpListAdapter(Contacts.this);
    	expandableListView.setAdapter(adapter);
    	expandableListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				String gname = groupArray.get(groupPosition).get("title");
				String cname = childArray.get(groupPosition).get(childPosition).get("title");
				String groupBtn_id = "g" + groupPosition;
				String childBtn_id = groupPosition + "c" + childPosition;
				CheckBox checkBox = (CheckBox) v.findViewById(R.id.childCheckBox);
				checkBox.toggle();
				if (childCheckBox.get(groupPosition).get(childPosition).get(C_CB)) {
					childCheckBox.get(groupPosition).get(childPosition).put(C_CB, false);
										
					removeBtn(childBtn_id);
					if (groupCheckBox.get(groupPosition).get(G_CB)) {
						groupCheckBox.get(groupPosition).put(G_CB, false);
						removeBtn(groupBtn_id);
						for (int i = 0; i < childCheckBox.get(groupPosition).size(); i++) {
							if (childPosition != i) {
								String childBtn_id1 = groupPosition + "c" + i;
								String cname1 = childArray.get(groupPosition).get(i).get("title");
								childCheckBox.get(groupPosition).get(i).put(C_CB, true);
								Button btn1 = createChildBtn(cname1, groupPosition, childPosition, childBtn_id1, adapter);
								addBtn(childBtn_id1, btn1);
							}
						}
					}
				} else {
					int count = 0;
					childCheckBox.get(groupPosition).get(childPosition).put(C_CB, true);
					Button btn2 = createChildBtn(cname, groupPosition, childPosition, childBtn_id, adapter);
					addBtn(childBtn_id, btn2);
					for (int i = 0; i < childCheckBox.get(groupPosition).size(); i++) {
						if (childCheckBox.get(groupPosition).get(i).get(C_CB)) {
							count += 1;
						}
					}
					if (count == childCheckBox.get(groupPosition).size()) {
						groupCheckBox.get(groupPosition).put(G_CB, true);
						Button btn3 = createBtn(groupPosition, gname, adapter);
						addBtn(groupBtn_id, btn3);
						for (int j = 0; j < childCheckBox.get(groupPosition).size(); j++) {
							String childBtn_id2 = groupPosition + "c" + j;
							removeBtn(childBtn_id2);
						}
					}
				}
				reSetBtn();
				adapter.notifyDataSetChanged();
				return false;
			}
		});
    }
    
    /**
     *  初始化groupArray, childArray, groupCheckBox, childCheckBox数据
     */
    private void initContacts(){
    	
    	// 定义发送请求的URL
    	String url = HttpUtil.BASE_URL + "contacts.jsp";
    	
		try
		{
			// 发送请求
	    	JSONObject jsonObj = new JSONObject(HttpUtil.getRequest(url));
	    	
	    	JSONArray groupArrayTemp = jsonObj.getJSONArray("groupArray");
	    	
	    	JSONArray childArrayTemp = jsonObj.getJSONArray("childArray");
	    	
	    	
	    	
	    	for(int i=0,length=groupArrayTemp.length();i<length;i++)
	    	{
	    		Map<String, String> groupMap = new HashMap<String, String>();
	    		
	    		groupMap.put("title", groupArrayTemp.getJSONObject(i).getString("title"));
	    		
	    		groupArray.add(groupMap);
	    	}
	    	
	    	for (int i = 0,length=childArrayTemp.length(); i < length; i++) {
	    		
	    		Map<String, Boolean> curGB = new HashMap<String, Boolean>();
				curGB.put(G_CB, false);
				groupCheckBox.add(curGB);
				
				List<Map<String, String>> t = new ArrayList<Map<String, String>>();
				List<Map<String, Boolean>> childCB = new ArrayList<Map<String,Boolean>>();
				
				for (int j = 0,lengthTemp=childArrayTemp.getJSONArray(i).length(); j < lengthTemp; j++) {
					
					Map<String, Boolean> curCB = new HashMap<String, Boolean>();
					curCB.put(C_CB, false);
					
					Map<String, String> childMap = new HashMap<String, String>();
					
					childMap.put("title", childArrayTemp.getJSONArray(i).getJSONObject(j).getString("title"));
					childMap.put("aid", childArrayTemp.getJSONArray(i).getJSONObject(j).getString("aid"));
					
					t.add(childMap);
					childCB.add(curCB);
				}
				
				childArray.add(t);
				childCheckBox.add(childCB);
			}
	    	
	    	//通讯录回显
	    	String userId = preferences.getString("userId", null);
	    	
	    	if (null!=preferences.getString(userId+"GID", null)&&!"".equals(preferences.getString(userId+"GID", null))) 
	    	{
	    		String[] strings = preferences.getString(userId+"GID", null).split(",");
	    		
	    		for (int i = 0,length=groupArray.size(); i < length; i++) {
	    			
	    			for (String string:strings) 
	    			{
	    				if (string.equals(groupArray.get(i).get("title"))) 
	    				{
	    					groupCheckBox.get(i).put(G_CB, true);
	    				}
	    			}
	    		}
	    	}
	    	
	    	
	    	if (null!=preferences.getString(userId+"AID", null)&&!"".equals(preferences.getString(userId+"AID", null))) 
	    	{
	    		String[] strings = preferences.getString(userId+"AID", null).split(",");
		    	
		    	for (int i = 0,length=childArray.size(); i < length; i++) {
					
		    		for (int j = 0,lengthTemp=childArray.get(i).size(); j < lengthTemp; j++) {
						for (String string:strings) 
						{
							if (string.equals(childArray.get(i).get(j).get("aid"))) 
							{
								childCheckBox.get(i).get(j).put(C_CB, true);
							}
						}
		    			
					}
				}
			}
	    	
		}
		catch (Exception e)
		{
			DialogUtil.showDialog(this, "服务器响应异常，请稍后再试！", false);
			e.printStackTrace();
		}

    }
    
    public class MyExpListAdapter extends BaseExpandableListAdapter{
    	private Context context;
    	ViewHolder holder;
    	public MyExpListAdapter(Context context){
    		this.context = context;
    	}

		@Override
		public int getGroupCount() {
			return groupArray.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return childArray.get(groupPosition).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return groupArray.get(groupPosition).get("title");
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return childArray.get(groupPosition).get(childPosition).get("title");
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}
		
		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		@Override
		public View getGroupView(final int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			View v = convertView;
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.contacts_group_item, null);
			}
			TextView groupText = (TextView) v.findViewById(R.id.groupText);
			final CheckBox gCheckBox = (CheckBox) v.findViewById(R.id.groupCheckBox);
			final String gname = groupArray.get(groupPosition).get("title");
			groupText.setText(gname);
			gCheckBox.setChecked(groupCheckBox.get(groupPosition).get(G_CB));
			gCheckBox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Boolean isChecked = gCheckBox.isChecked();
					String btn_id = "g" + groupPosition;
					if (isChecked) {
						Button btn = createBtn(groupPosition, gname, MyExpListAdapter.this);
						addBtn(btn_id, btn);
					} else {
						removeBtn(btn_id);
					}
					groupCheckBox.get(groupPosition).put(G_CB, isChecked);
					changChildStates(groupPosition, isChecked);
					reSetBtn();
					notifyDataSetChanged();
				}
			});
			return v;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.contacts_child_item, null);
				holder = new ViewHolder();
				holder.cText = (TextView) convertView.findViewById(R.id.childText);
				holder.checkBox = (CheckBox) convertView.findViewById(R.id.childCheckBox);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.cText.setText(childArray.get(groupPosition).get(childPosition).get("title"));
			holder.checkBox.setChecked(childCheckBox.get(groupPosition).get(childPosition).get(C_CB));
			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
    	
    }
    
    private void changChildStates(int groupPosition, Boolean isChecked) {
		for (int i = 0; i < childCheckBox.get(groupPosition).size(); i++) {
			childCheckBox.get(groupPosition).get(i).put(C_CB, isChecked);
			String c_id = groupPosition + "c" + i;
			removeBtn(c_id);
		}
	}
    
	private Button createBtn(final int groupPosition, final String gname, final MyExpListAdapter adapter) {
		final Button btn = new Button(Contacts.this);
		btn.setText(gname + "    X");
		btn.setTextSize(TEXTSIZE);
		btn.getBackground().setAlpha(TOUMD);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btn_layout.removeView(btn);
				groupCheckBox.get(groupPosition).put(G_CB, false);
				changChildStates(groupPosition, false);
				adapter.notifyDataSetChanged();
			}
		});
		return btn;
	}
	
	private Button createChildBtn(String cname, final int groupPosition, final int childPosition, final String btn_id, final MyExpListAdapter adapter){
		final Button btn = new Button(Contacts.this);
		btn.setText(cname + "    X");
		btn.setTextSize(TEXTSIZE);
		btn.getBackground().setAlpha(TOUMD);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				btn_layout.removeView(btn);
				childCheckBox.get(groupPosition).get(childPosition).put(C_CB, false);
				removeBtn(btn_id);
				reSetBtn();
				adapter.notifyDataSetChanged();
			}
		});
		return btn;
	}
	
	private void addBtn(String btn_id, Button btn) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("btn", btn);
		map.put("btn_id", btn_id);
		int count = 0;
		if (btnArray.size() > 0) {
			for (int i = 0; i < btnArray.size(); i++) {
				if (btnArray.get(i).get("btn_id").equals(btn_id)) {
					count += 1;
				}
			}
		}
		if (count == 0) {
			btnArray.add(map);
		}
	}
	
	private void removeBtn(String btn_id) {
		
		if (btnArray.size() > 0) {
			for (int i = 0; i < btnArray.size(); i++) {
				String button_id = (String) btnArray.get(i).get("btn_id");
				if (button_id.equals(btn_id)) {
					btnArray.remove(i);
				}
			}
		}
	}
	
	private void reSetBtn() {
		atEditBtn = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		atEditBtn.gravity = Gravity.CENTER;
			btn_layout.removeAllViews();
			for (int i = 0; i < btnArray.size(); i++) {
				Button btn = (Button) btnArray.get(i).get("btn");
				btn_layout.addView(btn, atEditBtn);
			}
	}
    
	private static class ViewHolder {
		TextView cText;
		CheckBox checkBox;
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Toast.makeText(getApplicationContext(), "待扩展。。。\n\n河南卓辉通信技术有限公司版权所有",  Toast.LENGTH_LONG).show();
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		String userId = preferences.getString("userId", null);
		
		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences("com.drow.aips", MODE_WORLD_READABLE);
		editor = preferences.edit();
				
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
		{

			StringBuilder builder = new StringBuilder();
			
			for (int i = 0,length=groupCheckBox.size(); i <length ; i++) {
				
				if (groupCheckBox.get(i).get(G_CB)) 
				{
					builder.append(groupArray.get(i).get("title")+",");
				}
			}
		
			// 删除旧的用户名
			editor.remove(userId+"GID");
			// 存入当前用户名
			editor.putString(userId+"GID", builder.toString());
			
			
			builder.delete(0, builder.length());
			
			
			for (int i = 0,length=childCheckBox.size(); i <length ; i++) {
				
				for (int j = 0,lengthTemp=childCheckBox.get(i).size(); j < lengthTemp; j++) {
					
					if (childCheckBox.get(i).get(j).get(C_CB)) 
					{
						builder.append(childArray.get(i).get(j).get("aid")+",");
					}
					
				}
			}
			
			// 删除旧的用户名
			editor.remove(userId+"AID");
			// 存入当前用户名
			editor.putString(userId+"AID", builder.toString());
			
			// 提交所有存入的数据
			editor.commit();
			
			String aIds = null; 
					
			if (!"".equals(builder.toString())) {
				aIds = builder.toString();
			}
			
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			
	    	bundle.putString("aIds", aIds);
	    	
	    	intent.putExtras(bundle);
			setResult(20, intent);//设置返回数据
			
			builder = null;
			
			// 结束该Activity
			finish();
			
		}else if(keyCode == KeyEvent.KEYCODE_MENU) 
		{
			Toast.makeText(getApplicationContext(), "待扩展。。。\n\n河南卓辉通信技术有限公司版权所有",  Toast.LENGTH_LONG).show();
		}
		return true;
	}
}